package com.zt.filter;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.zt.utils.common.dtos.ResponseResult;
import com.zt.utils.login.JwtToken;
import io.jsonwebtoken.Claims;
import lombok.extern.apachecommons.CommonsLog;
import nonapi.io.github.classgraph.json.JSONUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Author: 王佳祥
 * @Date: 2024 09 06 20:09
 */
@Component
public class LoginFilter implements GlobalFilter {
    private static  final String  LOGIN_URL="login";
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
//        1.如果路径中包含login则放行
        if(path.contains(LOGIN_URL)){
            return chain.filter(exchange);
        }
//       2. 如果没有则看看是够包含token
        String token = request.getHeaders().getFirst("Authorization");
//       3. 判断token是否为空
        if(token==null){
            response.getHeaders().add("Content-Type","application/json");
            String s = JSONUtil.toJsonStr(ResponseResult.errorResult(401,"token不存在"));
            DataBuffer wrap = response.bufferFactory().wrap(s.getBytes());
            return response.writeWith(Mono.just(wrap));
        }
//        如果token不为空则对token进行校验
        try{
//            校验token是否有效
            JwtToken.resolveJwt(token);

        }catch (Exception e){
//            解密失败
            response.getHeaders().add("Content-Type","application/json");
            String s = JSONUtil.toJsonStr(ResponseResult.errorResult(402,"token无效"));
            DataBuffer wrap = response.bufferFactory().wrap(s.getBytes());
            return response.writeWith(Mono.just(wrap));
        }
        return chain.filter(exchange);
    }
}


